﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Configuration;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Security.AccessControl;
using System.Deployment;
using System.Deployment.Application;
using System.Security.Principal;
using System.Management;
using Microsoft.Win32;

namespace EncircleFTM
{
     
    static class Program
    {
       
        /// <summary>
        /// The main entry point for the application.
        /// </summary>

        [STAThread]
        static void Main()
        {
            string strMessage1 = string.Empty;
            string strMessage2 = string.Empty;
            bool IsRightsAvailable = false;
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                rk.SetValue("ECHO", Application.ExecutablePath.ToString());

                KillProcess("Scheduler.exe", true);
                KillProcess("EncircleFTM.exe", false);
                
                string strCurrentUser = System.Environment.UserName;
                string strEveryoneUser = "EVERYONE";
           
                string strAppPath = clsCommonData.GetAppPath();

                if (!clsCommonData.CheckFolderAccessRights(strAppPath, strEveryoneUser, ref strMessage2))
                {
                    DirectoryInfo dInfo = new DirectoryInfo(strAppPath).Parent;
                    DirectorySecurity dSecurity = dInfo.GetAccessControl();
                    dSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
                    dInfo.SetAccessControl(dSecurity);
                }

                if (clsCommonData.CheckFolderAccessRights(strAppPath, strEveryoneUser, ref strMessage2)) IsRightsAvailable = true;

                if (IsRightsAvailable)
                {
                    ////Read application settings
                    clsSettings.ReadSettings();

                    //Installing Echo Printer
                    InstallEchoPrinter.installPrinter();

                    //Clearing Logs                    
                    clsCommonData.StartScheduler();
                    Application.Run(new frmStatusMonitor());
                    clsCommonData.StopScheduler();
                }
                else
                {
                    var info = new DirectoryInfo(Application.ExecutablePath).Parent.Parent.FullName;
                    MessageBox.Show(string.Format("Everyone user Rights validation status:**{0}.\r\n" +
                       "Path:" + info, strMessage2), "ECHO");
                }
            }
            catch (Exception ex)
            {
                if (!IsRightsAvailable)
                {
                    var info = new DirectoryInfo(Application.ExecutablePath).Parent.Parent.FullName;
                    MessageBox.Show(string.Format("Everyone user Rights validation status:**{0}.\r\n" +
                       "Path:" + info, strMessage2), "ECHO");
                }

                clsCommonData.WriteError(ex.ToString());
            }        
        }

        static void KillProcess(string processName, bool KillAll)
        {
            string User = String.Empty;
            string ProcessStr = String.Empty;
            Dictionary<int, string> runningProcesses = new Dictionary<int, string>();
            ObjectQuery WMIQuery = new ObjectQuery("Select * from Win32_Process where Name = '" + processName + "'");
            ManagementObjectSearcher WMIResult = new ManagementObjectSearcher(WMIQuery);
            foreach (ManagementObject oItem in WMIResult.Get())
            {
                string[] List = new String[2];
                oItem.InvokeMethod("GetOwner", (object[])List);
                ProcessStr = (string)oItem["Name"];
                User = List[0];
                if (User == null) User = String.Empty;
                runningProcesses.Add(Convert.ToInt32(oItem["ProcessId"]), User);
            }
            var currentUserProcesses = runningProcesses.Where(m => m.Value.Equals(System.Environment.UserName));
            if (currentUserProcesses.Count() > 0 && KillAll)
            {                
                foreach (var process in currentUserProcesses)
                {
                    Process temp = Process.GetProcessById(process.Key);
                    temp.Kill();
                }
            }
            if (currentUserProcesses.Count() > 1 && KillAll)
            {
                var MaxProcID = currentUserProcesses.Max(m => m.Key);
                foreach (var process in currentUserProcesses)
                {
                    if (process.Key != MaxProcID) { Process temp = Process.GetProcessById(process.Key); temp.Kill(); }
                }
            }


        }

        static void CurrentDeployment_UpdateCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            Application.Restart();
        }
        public static void DownLoadFileInBackground(string address,string filename)
        {
            WebClient client = new WebClient();
            Uri uri = new Uri(address);
            client.DownloadFileCompleted += (sender, e) =>
                                            {
                                                //inspect e here:
                                                //e.Error
                                            };
            client.DownloadProgressChanged += (sender, e) =>
                                              {
                                                  //e.ProgressPercentage
                                              };
            client.DownloadFileAsync(uri, filename);
        }

        //public string[] getversion()
        //{
        //    string[] versiondetails = new string[5];
        //    //objVersionDelegate = new VersionDelegate(VersionDetails);

        //    //EncircleFTM.EncircleDataUpload.Versioninfo objVersionInfo = VersionDetails();
        //    versiondetails[0] = "EncricleECHO_Setup.msi";
        //    versiondetails[1] = "1/0";
        //    return versiondetails;
        //}
        //static void UpdateApplication(EncircleDataUpload.Versioninfo objversion)
        //{
        //    if (objversion != null)
        //    {
        //        if (objversion.Filename != string.Empty)
        //        {
        //            var CurrentVersion = Convert.ToDouble(Application.ProductVersion.Substring(0, Application.ProductVersion.IndexOf('.', 2)));
        //            //var UpdateVersion = Convert.ToDouble(GetRemoteVersion());
                   

        //            // string[] getversioninfo = getversion();
        //            string filename = objversion.Filename;
                  
        //            var UpdateVersion = Convert.ToDouble(objversion.Fileversion);
        //            string updateversion = Convert.ToString(UpdateVersion);
        //            if (UpdateVersion > CurrentVersion)
        //            {
        //                DownloadUpdate(updateversion, filename);
        //            }
        //        }
        //    }
        //}

        //static string GetRemoteVersion()
        //{
        //    EncircleDataUpload.ServiceSoapClient service = new EncircleDataUpload.ServiceSoapClient();
        //    return service.CheckVersion();
        //}

        static void DownloadUpdate(string UpdateVersion,string filename)
        {
            //System.Diagnostics.Debugger.Launch();
            
            DialogResult dlg = MessageBox.Show("A New Version of ECHO Available.Do you want to Download it","ECHO",MessageBoxButtons.OKCancel);
            if (dlg == DialogResult.OK)
            {
                                //FolderBrowserDialog dialog = new FolderBrowserDialog();
                //dialog.RootFolder = Environment.SpecialFolder.DesktopDirectory;
                //dialog.ShowDialog();
                //var targetPath = dialog.SelectedPath;
                ////string downloadFilename = "EncricleECHO_Setup" + "UpdateVersion"+".msi";
                string downloadFilename = filename;
                WebClient client = new WebClient();
                //string DownloadURL=ConfigurationSettings.AppSettings["WebsiteURL"].ToString()+"/"+ downloadFilename;
                ////DownLoadFileInBackground(DownloadURL, downloadFilename);
                //try
                //{
                //    client.DownloadFile(DownloadURL, downloadFilename);
                //}
                //catch (Exception ex)
                //{

                //}

                Type InstallerType;
                WindowsInstaller.Installer installer;
                InstallerType = Type.GetTypeFromProgID("WindowsInstaller.Installer");
                installer = (WindowsInstaller.Installer)Activator.CreateInstance(InstallerType);

                var installationPath = Application.StartupPath;
                //if(!Directory.Exists("C:\\Updateinstaller"))
                //{
                //    Directory.CreateDirectory("C:\\Updateinstaller");
                //}
                //var process = new System.Diagnostics.Process();
                //process.StartInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe", "/k" + "C:\\Updateinstaller" + downloadFilename);
                //process.Start();
                //process.WaitForExit();
               // string targetPath = @"c:\\Updateinstaller";
                System.Diagnostics.Process installerProcess= new System.Diagnostics.Process();
               // installerProcess = System.Diagnostics.Process.Start("msiexec.exe", "TARGETDIR=" + installationPath + " /i " + targetPath + @"\" + downloadFilename + " REINSTALLMODE=voums");
               // installerProcess=System.Diagnostics.Process.Start("msiexec.exe", "TARGETDIR=" + installationPath + " /i " + "http://206.135.141.11/ECHO/Setup/EncricleECHO_Setup1.2.msi");
                installerProcess.StartInfo.Arguments = "/fe" + downloadFilename;
                installerProcess.StartInfo.FileName = "http://206.135.141.11/ECHO/Setup/EncricleECHO_Setup1.2.msi";
                installerProcess.Start();
                while (installerProcess.HasExited == false)
                {
                    //indicate progress to user
                    MessageBox.Show("Installation is in progress");
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(1000);

                }
                //installerProcess.Dispose();
                //File.Delete(targetPath + @"\" + downloadFilename);
                MessageBox.Show("Updated Successfully...! Restart the application..!");
            }
        }
       //// static void startup(string[] args)
       // {
       //     //Check current Desktop user and Everyone user privillages
       //     string strCurrentUser = System.Environment.UserName;
       //     string strEveryoneUser = "EVERYONE";
       //     string strMessage1 = string.Empty;
       //     string strMessage2 = string.Empty;
       //     string strAppPath = clsCommonData.GetAppPath();
       //     if (!clsCommonData.CheckFolderAccessRights(strAppPath, strEveryoneUser, ref strMessage1))
       //     {
       //         if (!clsCommonData.CheckFolderAccessRights(strAppPath, strCurrentUser, ref strMessage2))
       //         {
       //             MessageBox.Show(string.Format("Everyone user Rights validation status:**{0}.\r\n" +
       //            "Current User Rights validation Status:**{1}.\r\n", strMessage1, strMessage2), "ECHO");
       //             return;
       //         }
       //     }

       //     string ArgumentVal = string.Empty;

       //     if (args.Length < 1) return;

       //     ArgumentVal = args[0];
       //     switch (ArgumentVal)
       //     {
       //         case "MONITOR":
       //             Process[] processList = Process.GetProcessesByName("EncircleFTM");
       //             if (processList.Length > 0)
       //             {

       //                 MessageBox.Show("Application is Already Running!", EncircleFTM.clsCommonData.STR_APPNAME, MessageBoxButtons.OK);
       //                 return;
       //             }
       //             string AppPath = System.Environment.CurrentDirectory;
       //             ProcessStartInfo startupProcess = new ProcessStartInfo(System.IO.Path.Combine(AppPath, "EncircleFTM.exe"));
       //             System.Diagnostics.Process.Start(startupProcess);
       //             break;

       //         case "ERRORLOG":
       //             EncircleFTM.frmViewErrorLog objViewErrorLog = new EncircleFTM.frmViewErrorLog();
       //             objViewErrorLog.ShowDialog();
       //             break;

       //         case "FILETRANSLOG":
       //             EncircleFTM.frmViewFileTransferLog objViewFileTransferLog = new EncircleFTM.frmViewFileTransferLog();
       //             objViewFileTransferLog.ShowDialog();
       //             break;

       //         case "ABOUT":
       //             EncircleFTM.frmAbout objAbout = new EncircleFTM.frmAbout();
       //             objAbout.ShowDialog();
       //             break;

       //         case "HELP":
       //             EncircleFTM.frmHelp objHelp = new EncircleFTM.frmHelp();
       //             objHelp.ShowDialog();
       //             break;
       //     }
 
    
    }
}
